package com.itjin.resume_back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.resume_back.common.Result;
import com.itjin.resume_back.entity.Resume;
import com.itjin.resume_back.service.ResumeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 简历控制器
 * 提供简历相关的接口，包括上传、更新、删除、查询等功能
 */
@Tag(name = "简历管理", description = "简历相关的接口，包括上传、更新、删除、查询等功能")
@RestController
@RequestMapping("/api/resume")
@RequiredArgsConstructor
public class ResumeController {

  private final ResumeService resumeService;

  /**
   * 上传简历
   * 
   * @param userId      用户ID
   * @param title       简历标题
   * @param description 简历描述
   * @param file        简历文件
   * @param tags        标签（可选）
   * @return 操作结果
   */
  @Operation(summary = "上传简历", description = "上传新的简历文件")
  @PostMapping("/upload")
  public Result<String> uploadResume(
      @Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
      @Parameter(description = "简历标题", required = true) @RequestParam("title") String title,
      @Parameter(description = "简历描述", required = true) @RequestParam("description") String description,
      @Parameter(description = "简历文件", required = true) @RequestParam("file") MultipartFile file,
      @Parameter(description = "标签", required = false) @RequestParam(value = "tags", required = false) String tags) {
    try {
      resumeService.uploadResume(userId, title, description, file, tags);
      return Result.success("简历上传成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 更新简历
   * 
   * @param id          简历ID
   * @param title       简历标题
   * @param description 简历描述
   * @param file        简历文件（可选）
   * @param tags        标签（可选）
   * @return 操作结果
   */
  @Operation(summary = "更新简历", description = "更新简历信息，可选择是否更新简历文件")
  @PutMapping("/update")
  public Result<String> updateResume(
      @Parameter(description = "简历ID", required = true) @RequestParam("id") Long id,
      @Parameter(description = "简历标题", required = true) @RequestParam("title") String title,
      @Parameter(description = "简历描述", required = true) @RequestParam("description") String description,
      @Parameter(description = "简历文件", required = false) @RequestParam(value = "file", required = false) MultipartFile file,
      @Parameter(description = "标签", required = false) @RequestParam(value = "tags", required = false) String tags) {
    try {
      resumeService.updateResume(id, title, description, file, tags);
      return Result.success("简历更新成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 删除简历
   * 
   * @param id 简历ID
   * @return 操作结果
   */
  @Operation(summary = "删除简历", description = "删除指定简历")
  @DeleteMapping("/delete")
  public Result<String> deleteResume(
      @Parameter(description = "简历ID", required = true) @RequestParam("id") Long id) {
    try {
      resumeService.deleteResume(id);
      return Result.success("简历删除成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取简历列表
   * 
   * @param userId 用户ID
   * @param page   页码
   * @param size   每页大小
   * @return 分页简历列表
   */
  @Operation(summary = "获取简历列表", description = "分页获取用户的简历列表")
  @GetMapping("/list")
  public Result<Page<Resume>> listResumes(
      @Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
      @Parameter(description = "页码", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
      @Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") Integer size) {
    try {
      Page<Resume> pageParam = new Page<>(page, size);
      LambdaQueryWrapper<Resume> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(Resume::getUserId, userId);
      wrapper.orderByDesc(Resume::getCreateTime);
      Page<Resume> resumePage = resumeService.page(pageParam, wrapper);
      return Result.success(resumePage);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取简历详情
   * 
   * @param id 简历ID
   * @return 简历详情
   */
  @Operation(summary = "获取简历详情", description = "获取指定简历的详细信息")
  @GetMapping("/detail")
  public Result<Resume> getResumeDetail(
      @Parameter(description = "简历ID", required = true) @RequestParam("id") Long id) {
    try {
      Resume resume = resumeService.getById(id);
      if (resume != null) {
        return Result.success(resume);
      } else {
        return Result.error("简历不存在");
      }
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 下载简历文件
   * 
   * @param id 简历ID
   * @return 简历文件
   */
  @Operation(summary = "下载简历文件", description = "下载指定简历的文件")
  @GetMapping("/download")
  public ResponseEntity<byte[]> downloadResume(
      @Parameter(description = "简历ID", required = true) @RequestParam("id") Long id) {
    try {
      Resume resume = resumeService.getById(id);
      if (resume == null) {
        return ResponseEntity.notFound().build();
      }

      byte[] fileData = resumeService.getResumeFile(id);

      // 获取文件扩展名
      String fileUrl = resume.getFileUrl();
      String fileExtension = fileUrl.substring(fileUrl.lastIndexOf("."));

      // 根据文件扩展名设置Content-Type
      MediaType mediaType;
      if (".pdf".equalsIgnoreCase(fileExtension)) {
        mediaType = MediaType.APPLICATION_PDF;
      } else if (".doc".equalsIgnoreCase(fileExtension) || ".docx".equalsIgnoreCase(fileExtension)) {
        mediaType = MediaType.parseMediaType("application/msword");
      } else {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
      }

      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(mediaType);
      // 设置文件名，使用URL编码确保中文文件名正确显示
      String encodedFileName = java.net.URLEncoder.encode(resume.getTitle() + fileExtension, "UTF-8")
          .replaceAll("\\+", "%20");
      headers.setContentDispositionFormData("attachment", encodedFileName);
      headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
      headers.setContentLength(fileData.length);

      return ResponseEntity.ok()
          .headers(headers)
          .body(fileData);
    } catch (Exception e) {
      return ResponseEntity.badRequest().build();
    }
  }
}